package com.mm.dds.controller;

import com.mm.dds.datasource.DataSourceContextHolder;
import com.mm.dds.datasource.SetDynamicDataSource;
import com.mm.dds.service.DdsTestService;
import com.mm.utils.ResponseBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
public class DdsTestController {

    @Autowired
    private DdsTestService ddsTestService;

    //获取全部公司信息
    @RequestMapping("getCompanyList")
    public ResponseBean getCompanyList() {

        DataSourceContextHolder.setDBType("default");
        List list = ddsTestService.getCompanyList();
        return new ResponseBean(200, "获取成功", list);
    }

    //录入新公司信息，同时生成其相应的数据库以及在数据库内建立模板表
    @RequestMapping("insertCompany")
    public ResponseBean insertCompany(@RequestBody Map map) {

        DataSourceContextHolder.setDBType("default");
        ddsTestService.insertCompany(map);
        String companyDbName=this.createCompanyDb();
        this.createCompanyDbTable(companyDbName);
        String companyid = companyDbName.substring(companyDbName.lastIndexOf("_")+1);
        return new ResponseBean(200, "保存成功", companyid);
    }

    //建数据库
    public String createCompanyDb(){

        DataSourceContextHolder.setDBType("default");
        String companyDbName=ddsTestService.selectLastCompanyId();
        ddsTestService.createCompanyDb(companyDbName);
        return companyDbName;

    }

    //建模板表
    private void createCompanyDbTable(String companyDbName) {

        SetDynamicDataSource.setDDS(companyDbName);
        ddsTestService.createCompanyDbTable("company_info");

    }

    //删除公司记录同时删除相应的数据库
    @GetMapping("/deleteCompany/{companyid}")
    public ResponseBean deleteCompany(@PathVariable("companyid") int companyid){

        ddsTestService.deleteCompanyById(companyid);

        return new ResponseBean(200,"deleteOk",null);
    }


}
